package com.ita.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.ita.dao.MUserDao;
import com.ita.pojo.MUser;

@Repository(value="merchantDao")
public class MUserDaoImpl implements MUserDao {

	@PersistenceContext(name = "unit")
	private EntityManager manager;

	@Override
	public MUser add(MUser mUser) {

		manager.persist(mUser);
		return mUser;
	}

	@Override
	public List<MUser> findAll() {

		String pql = "select m from Muser m";
		List<MUser> list = manager.createQuery(pql).getResultList();
		return list;
	}

	@Override
	public int UpdateBlock(String id, int block) {
		int  result = 0;
		try {
			String pql = "update MUser m set m.block=:block where m.id=:id";
			result = manager.createQuery(pql).setParameter("block", block).setParameter("id", id).executeUpdate();
		} catch (Exception e) {
			return result;
		}
		return result;
	}

	@Override
	public MUser getByName(String name) {

		MUser mUser = null;
		try {
			String pql = "select m from MUser m where m.name=:name";
			mUser = (MUser) manager.createQuery(pql).setParameter("name", name).getSingleResult();
		} catch (Exception e) {
			return mUser;
		}
		return mUser;
	}

	@Override
	public MUser getById(String id) {
		MUser mUser = null;
		try {
			mUser = manager.find(MUser.class, id);
			manager.merge(mUser);
		} catch (Exception e) {
			return mUser;
		}
		return mUser;
	}

	@Override
	public MUser update(MUser mUser) {

		MUser newMUser = manager.find(MUser.class, mUser.getId());
		newMUser.setAddress(mUser.getAddress());
		newMUser.setBlock(mUser.getBlock());
		newMUser.setIdcard(mUser.getIdcard());
		newMUser.setImg(mUser.getImg());
		newMUser.setMsg(mUser.getMsg());
//		newMUser.setName(mUser.getName());
		// newMUser.setPwd(mUser.getPwd());
		newMUser.setState(mUser.getState());
		newMUser.setStore_name(mUser.getStore_name());
		// newMUser.setSubmit_time(mUser.getSubmit_time());
		// newMUser.setVerify_time(mUser.getVerify_time());
		manager.merge(newMUser);
		return newMUser;
	}

	@Override
	public MUser update(String id, int block, int state) {
		// TODO Auto-generated method stub
		MUser  m = null;
		try {
			String pql = "update MUser m set m.block=:block, m.state=:state where m.id=:id";
			manager.createQuery(pql).setParameter("block", block).setParameter("id", id).setParameter("state", state).executeUpdate();
			m=manager.find(MUser.class, id);
		} catch (Exception e) {
			return m;
		}
		return m;
	}

}
